<template>
  <div class="jbc-container">
    <jbc-menu />
    <div class="jbc-payment" v-loading="infoLoading">
      <el-breadcrumb v-if="pathList.length" style="margin-top: 5px;padding: 12px 0 20px;" :separator-icon="ArrowRight">
        <el-breadcrumb-item v-for="path in pathList" :key="path.id" :to="path.url">{{ path.name }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="jbc-box">
        <div class="claim-goods">
          <div class="claim-goods-title custom-title">取货方式</div>
          <el-radio-group v-model="logisticsType" class="claim-btn" size="large">
            <el-radio-button label="快递" value="1" />
            <el-radio-button label="物流" value="2" />
            <el-radio-button label="自提" value="3" />
          </el-radio-group>
          <el-collapse-transition>
            <div class="address-box" v-show="logisticsType !== '3'">
              <div class="address-title custom-title"><el-button icon="Plus" @click="handleEditAddress">新增地址</el-button>
              </div>
              <el-row :gutter="20" class="address-list">
                <el-col :span="8" v-for="(item, index) in address.dataList" :key="index">
                  <div class="address-item" :class="{ active: item.id === addressid }"
                    @click="handleSelectAddress(item)">
                    <div class="address-item__icon">
                      <el-icon :size="30">
                        <LocationFilled v-if="item.id === addressid" />
                        <Location v-else />
                      </el-icon>
                    </div>
                    <div class="address-item__info">
                      <div class="address-item__title">
                        <span v-show="item.isDefault === 'Y'" class="default">默认</span>
                        <span class="name">{{ item.consignorName }}</span>
                        <span class="phone">{{ item.phone }}</span>
                      </div>
                      <div class="address-item__content" :title="addressDisplay(item)">
                        <el-text truncated>
                          {{ addressDisplay(item) }}
                        </el-text>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
              <addressForm ref="dataFormRef" @change="bindChangeList"></addressForm>
            </div>
          </el-collapse-transition>
        </div>
      </div>
      <div class="jbc-box">
        <shoppingCartGoodsList title="请确认订单信息" :goods-list="shopList" :count="selectCount"></shoppingCartGoodsList>
      </div>
    </div>
    <bottomOperate :select-count="selectCount" :select-price="totalPrice" :btn-txt="btnTxt" :loading="loading"
      @submit="bindSubmit">
      <div class="payment-box">
        <div class="payment-info">
          <div v-show="payTypeShow" class="payment-info-title custom-title">选择支付方式</div>
          <div v-show="payTypeShow" class="payment-info-list">
            <el-radio-group v-model="payType" :disabled="payTypeDisabled" class="pay-type">
              <el-radio value="3" size="large" border><el-avatar shape="square" fit="contain" :size="32"
                  :src="wxPay" />微信</el-radio>
              <el-radio value="2" size="large" border><el-avatar shape="square" fit="contain" :size="32"
                  :src="alpay" />支付宝</el-radio>
              <el-radio value="4" size="large" border><el-avatar shape="square" fit="contain" :size="32"
                  :src="uppay" />银联支付</el-radio>
              <el-radio value="5" size="large" border><el-avatar shape="square" fit="contain" :size="32"
                  :src="rspay" />钱包余额支付</el-radio>
            </el-radio-group>
          </div>
          <div class="payment-info-remark">
            <el-input v-model="remark" autosize type="textarea" placeholder="如有其他要求请备注" />
          </div>
        </div>
      </div>
    </bottomOperate>
    <custom-dialog :title="state.title" width="455" custom-class="custom-web" v-model="state.isVisible"
      :disabled="state.disabled" @close="handleCommand('close', $event)">
      <div class="view" v-loading="infoLoading">
        <div class="tips">请使用{{ state.type }}扫一扫，扫描二维码支付</div>
        <div class="number">{{ $numberPriceDisplay(state.totalPrice) }}</div>
        <div class="code">
          <qrCodeVue :value="state.value" :size="state.size" level="L"></qrCodeVue>
          <div v-show="state.idRefresh" class="refresh" @click="bindSubmit(1, true)">
            <el-icon>
              <Refresh />
            </el-icon>
          </div>
        </div>
        <div class="time">
          <el-countdown style="--el-statistic-content-font-size:16px" format="m分ss秒" :value="state.seconds"
            suffix="后支付二维码失效" @finish="bindTimeEnd" />
          <div class="refresh" @click="bindSubmit(1, true)">
            <el-icon>
              <Refresh />
            </el-icon>
          </div>
        </div>
      </div>
    </custom-dialog>
  </div>
</template>

<script setup name="PaymentOrder">
import { ArrowRight, Location, LocationFilled } from "@element-plus/icons-vue"
import { appOrderByIdGet, appOrderPayGet, appOrderGetPayStateGet } from '@/api/order'
import qrCodeVue from 'qrcode.vue'
import useAddressStore from '@/components/webCustom/address'
import addressForm from './account/components/addressForm'
import { dialogCustomStyle } from '@/components/webCustom/utils'
import wxPay from '../assets/common/payment/wxpay.png'
import alpay from '../assets/common/payment/alpay.png'
import uppay from '../assets/common/payment/uppay.png'
import rspay from '../assets/common/payment/rspay.png'
import payError from '../assets/common/payment/payError.png'
import { stubTrue } from "lodash"
import { onBeforeUnmount } from "vue"
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const address = useAddressStore()
const pathList = [{ id: '1', name: '首页', url: '/' }, { id: '2', name: '确认订单' }]
const loading = ref(false) // 底部按钮是否加载
const infoLoading = ref(true) // 底部信息区域是否加载
const btnTxt = ref('去支付') // 底部按钮文字
const totalPrice = ref(0) // 商品总价
const selectCount = ref(0) // 商品数量
const addressid = ref('') // 地址id
const shopList = ref([]) // 购物车列表
const remark = ref('') // 备注
const orderInfo = ref({}) // 订单信息

/* 地址操作区域 */
const dataFormRef = ref(null)
address.init()
const addressDisplay = (item) => {
  return `${item.province || ''}${item.city || ''}${item.district || ''}${item.address || ''}`
}
const bindChangeList = (val) => {
  address.setList().then((res) => {
    if (res && !addressid.value) {
      handleSelectAddress(res)
    }
  })
}
const handleEditAddress = () => {
  dataFormRef.value.show()
}
const handleSelectAddress = (item) => {
  addressid.value = item.id
  orderInfo.addressid = item.id
  orderInfo.consignorName = item.consignorName
  orderInfo.phone = item.phone
  orderInfo.province = item.province
  orderInfo.city = item.city
  orderInfo.district = item.district
}
const countdownInterval = ref(null);
const clearTimeInterval = () => {
  // 清除之前的间隔计时器（如果有）
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value)
    countdownInterval.value = null
  }
};
/* 支付操作区域 */
// 快递类型 1:快递 2:物流 3:自提-query
const logisticsType = ref('1')
// 1:审批 2:支付宝 3:微信 4:银联 5:钱包-query
const payType = ref('')
const payTypeDisabled = ref(true) // 支付方式是否禁用
const payTypeShow = ref(true)
route.params.id && appOrderByIdGet({ params: { id: route.params.id } }).then((res) => {
  orderInfo.value = res.data
  shopList.value = res.data.sellVos
  totalPrice.value = res.data.totalPrice
  state.totalPrice = res.data.totalPrice
  selectCount.value = res.data.sellVos.length
  addressid.value = res.data.addressid
  payType.value = res.data.payType
  logisticsType.value = res.data.logisticsType
  // 如果以前是银联支付不允许切换支付方式 如何获取以前的支付方式
  payTypeDisabled.value = res.data.payType === '4'
  payTypeShow.value = res.data.shopVo.type !== '2'
  btnTxt.value = res.data.shopVo.type === '1' ? '去支付' : '去提交'

  // 创建新的间隔计时器
  countdownInterval.value = setInterval(() => {
    checkOrderStatus()
  }, 10000);
}).catch((err) => {
  console.log(err)
}).finally(() => {
  infoLoading.value = false
})
const gotoOk = () => {
  router.push({ name: 'orderPayFinal', params: { id: route.params.id } })
}
const gotoOrder = () => {
  router.push({ name: 'order' })
}
const state = reactive({
  title: '',
  value: '',
  totalPrice: 0,
  type: '',
  seconds: 0,
  size: 178,
  isVisible: false,
  idRefresh: false,
  disabled: true
})
const bindTimeEnd = () => {
  state.idRefresh = stubTrue
}
const handleCommand = (command, payload) => {
  switch (command) {
    case 'close':
      state.isVisible = false
      break
  }
}

const bindSubmit = (e, close = false) => {
  if (!addressid.value) {
    proxy.$modal.confirm('<div style="font-weight: bold;font-size: 16px;color: #D6000F;line-height: 21px;">您需要填写您的收货地址，才能继续支付。</div>', { title: '无收货地址' }, {
      type: '',
      confirmButtonText: '去填写',
      dangerouslyUseHTMLString: true,
      draggable: true,
      customClass: 'custom-message-box',
      customStyle: dialogCustomStyle({ width: '572px' }),
      showClose: false
    }).then(action => {
      console.log('confirm', action)
      handleEditAddress()
    }).catch(action => {
      console.log('cancel', action)
    })
    return false
  }
  state.isVisible = close
  state.idRefresh = false
  loading.value = true
  appOrderPayGet({
    params: {
      id: route.params.id, // 订单ID string-query
      addressId: addressid.value, // 地址ID，除去自提类型不允许为空 string-query
      payType: payType.value, // 支付 1:审批 2:支付宝 3:微信 4:银联 5:钱包 string-query
      logisticsType: logisticsType.value, // 快递类型 1:快递 2:物流 3:自提 string-query
      bz: remark.value, // 备注 string-query
      refresh: e ? 'Y' : 'N' // 是否刷新二维码 Y:刷新 N:不刷新 (Y只用于弹窗刷新图标)-query
    }
  }).then((res) => {
    if (res.code === 0) {
      if (res.data.type === '2' || res.data.type === '3') {
        state.title = `${res.data.type === '2' ? '支付宝' : '微信'}支付`
        state.type = res.data.type === '2' ? '支付宝' : '微信'
        state.value = res.data.url
        state.seconds = Date.now() + parseInt(res.data.seconds) * 1000
        state.isVisible = true
      } else if (res.data.type === '4') {
        // 银联特殊处理
        proxy.$modal.confirm(`<div style="display: flex;flex-direction: column; font-weight: bold;font-size: 16px;color: #323232;line-height: 30px;">
          <div style="color: #D6000F;">请给如下银行汇款：</div>
          <div>收款银行：${res.data.accBlank}</div>
          <div>收款账户：${res.data.accName}</div>
          <div>收款账号：${res.data.accNo}</div>
          <div style="color: #D6000F;">汇款金额：${proxy.$numberAllPriceDisplay(totalPrice.value)}</div>
          </div>`, { title: '收款银行' }, {
          type: '',
          confirmButtonText: '查看订单',
          showCancelButton: false,
          dangerouslyUseHTMLString: true,
          draggable: true,
          customClass: 'custom-message-box',
          customStyle: dialogCustomStyle({ width: '405px' }),
          showClose: true
        }).then(action => {
          gotoOrder() // 查看订单
        }).catch(action => {
        })
      } else if (res.data.type === '1' || res.data.type === '5') {
        if (res.code === 0) {
          proxy.$modal.msgSuccess('支付成功')
          gotoOk()
        } else {
          payWaning()
        }
      }
    }
  }).catch((err) => {
    console.log(err)
  }).finally(() => {
    loading.value = false
  })
}
const checkOrderStatus = (flag) => {
  appOrderGetPayStateGet({ params: { id: route.params.id } }).then((res) => {
    if (res.code === 0 && res.data) {
      clearTimeInterval() // 停止计时器
      proxy.$modal.msgSuccess('支付成功')
      gotoOk() // 跳转到支付成功页面
    } else if (flag && res.code === 0 && !res.data) {
      state.isVisible = false // 关闭弹窗
      clearTimeInterval() // 停止计时器
      payWaning() // 提示支付失败
    }
  }).catch((err) => {
    clearTimeInterval() // 停止计时器
  })
}
const payWaning = () => {
  proxy.$modal.confirm('<div style="display: flex;flex-direction: column;align-items: center;"><img style="width: 192px;height: 104px;display: block;" src="' + payError + '" /><div style="font-weight: bold;font-size: 16px;color: #323232;line-height: 21px;">您的订单支付失败</div></div>', { title: '温馨提示' }, {
    type: '',
    confirmButtonText: '重新支付',
    cancelButtonText: '查看订单',
    dangerouslyUseHTMLString: true,
    draggable: true,
    customClass: 'custom-message-box',
    customStyle: dialogCustomStyle({ width: '385px' }),
    showClose: false
  }).then(action => {
    console.log('confirm', action)
    bindSubmit(payType.value === '2' || payType.value === '3') // 重新支付
  }).catch(action => {
    console.log('cancel', action)
    gotoOrder() // 查看订单
  })
}
onBeforeUnmount(() => {
  clearTimeInterval() // 停止计时器
})
</script>

<style lang="scss" scoped>
.jbc {
  &-payment {
    margin: 0 auto;
    width: var(--box-width);
  }

  &-box {
    background-color: #FFFFFF;
    border-radius: 20px;
    box-sizing: border-box;
    padding: 30px;

    &~& {
      margin-top: 20px;
    }
  }


}

.address {
  &-box {
    margin-top: 20px;
  }

  &-list {}

  &-item {
    display: flex;
    margin-top: 20px;
    border-radius: 18px;
    border: 1px solid #E6E8ED;
    padding: 20px;
    color: var(--jbc-font-color);
    user-select: none;
    cursor: pointer;

    &:hover,
    &.active {
      border-color: var(--jbc-color);
      background-color: #FFF9F9;

      .address-item__icon {
        color: var(--jbc-color);
      }
    }

    &__icon {
      margin-right: 12px;
    }

    &__info {
      flex: 1;
      width: 1px;
    }

    &__title {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      font-weight: bold;
      font-size: var(--jbc-font-size-large);
      line-height: 24px;

      & .default {
        color: #fff;
        background-color: var(--jbc-color);
        border-radius: 4px;
        font-size: var(--jbc-font-size-medium);
        line-height: 21px;
        padding: 0 5px 1px;
        font-weight: normal;
        margin-right: 5px;
      }

      & .name {}

      & .phone {
        margin-left: 10px;
      }
    }

    &__content {
      font-size: var(--jbc-font-size-medium);
      color: var(--jbc-font-color-light)
    }
  }
}

.payment {
  &-box {
    background-color: #FFFFFF;
    box-shadow: 0px 7px 11px 0px #F8F8F8;
    position: relative;
    z-index: 66666;
  }

  &-info {
    margin: 0 auto;
    width: var(--box-width);
    padding: 31px 0 26px;

    .payment-info-title {}

    .payment-info-list {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }

    .payment-info-remark {
      margin-top: 20px;
    }
  }
}

:deep(.pay-type) {
  margin-top: 20px;
  display: flex;
  width: 100%;

  .el-radio.is-bordered.el-radio--large {
    padding: 12px 20px;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-flow: row-reverse;
    height: auto;

    &.is-checked {
      border-color: var(--jbc-color);
    }

    .el-radio__input.is-checked .el-radio__inner {
      background-color: var(--jbc-color);
      border-color: var(--jbc-color);
    }

    .el-radio__label {
      display: flex;
      align-items: center;
      font-size: var(--jbc-font-size-medium);
      color: var(--jbc-font-color);

      .el-avatar {
        background-color: transparent;
        margin-right: 14px;
      }
    }
  }
}

:deep(.claim-btn) {
  margin-top: 20px;
  --el-color-primary: var(--jbc-color);
  --el-button-bg-color: #F8F8F8;
  --el-font-size-base: var(--jbc-font-size-medium);

  .el-radio-button {
    &__inner {
      padding: 12px 38px;
    }
  }
}

.view {
  display: flex;
  flex-direction: column;
  align-items: center;

  & .tips {
    font-weight: bold;
    font-size: 16px;
    color: #323232;
    line-height: 21px;
  }

  & .number {
    margin-top: 18px;
    font-weight: bold;
    font-size: 30px;
    color: #D6000F;
    line-height: 40px;
  }

  & .code {
    margin: 21px 0;
    position: relative;

    & .refresh {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 57px;
      background-color: rgba(255, 255, 255, 0.6);
      color: #232323;
      backdrop-filter: blur(3px);
      cursor: pointer;
    }
  }

  & .time {
    display: flex;
    align-items: center;

    .refresh {
      width: 21px;
      height: 21px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
  }
}
</style>